package com.scu.qingshi.domain.authorize.service;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scu.qingshi.domain.authorize.enums.AuthorizationStatusEnum;
import com.scu.qingshi.domain.authorize.param.LoginRequest;
import com.scu.qingshi.domain.authorize.param.RegistrationRequest;
import com.scu.qingshi.infrastructure.dao.po.User;
import com.scu.qingshi.infrastructure.dao.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 网络授权服务
 * @author qingshi
 */
@Service
public class AuthorizeService {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    UserService userService;

    public User register(RegistrationRequest req) throws Exception {
        User user = new User();
        try{
            user.setEmail(req.getEmail());
            user.setName(req.getName());
            user.setPhone(req.getPhone());
            user.setCreditNo(UUID.randomUUID().toString());
            user.setStatus(AuthorizationStatusEnum.REGISTERED.name());
            user.setPassword(req.getPassword());
            userService.save(user);

            return userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("email", req.getEmail()));
        }catch (Exception e){
            logger.error("注册入库失败, userData = {}",user);
            throw new Exception("注册入库失败"+e.toString());
        }
    }

    public User login(LoginRequest req) throws Exception {
        User user = null;
        try {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("email",req.getEmail())
                    .eq("password",req.getPassword())
                    .eq("status",AuthorizationStatusEnum.REGISTERED);
             user = userService.getBaseMapper().selectOne(wrapper);
        }catch (Exception e){
            logger.error("登陆失败, loginReq = {}",req);
            throw new Exception("登陆失败"+e.toString());
        }
        return user;
    }

}
